<template>
  <view class="device-replace-container">
    <uni-nav-bar title="门禁机替换" :border="false" background-color="#6fc16f" color="#fff" left-icon="left" @clickLeft="goBack">
    </uni-nav-bar>
    
    <view class="content-wrapper">
      <!-- 资料选择区域 -->
      <view class="select-section">
        <view class="section-title">
          <text class="title-text">选择资料</text>
        </view>
        
        <!-- 自定义搜索下拉框 -->
        <view class="custom-select-wrapper">
          <view class="select-input-wrapper" @click="toggleDropdown">
            <input 
              class="select-input"
              type="text"
              :value="searchText"
              placeholder="请搜索并选择资料（地址）"
              @input="onInputChange"
              @focus="showDropdown"
              @click.stop="focusInput"
              :focus="inputFocus"
            />
            <view class="select-icon" :class="{ 'rotate': isDropdownOpen }">
              <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
            </view>
            <view class="clear-icon" v-if="selectedAdsl" @click.stop="clearSelection">
              <uni-icons type="clear" size="16" color="#999"></uni-icons>
            </view>
          </view>
          
          <!-- 下拉选项列表 -->
          <view class="dropdown-wrapper" v-show="isDropdownOpen">
            <scroll-view 
              class="dropdown-list" 
              scroll-y 
              :style="{ maxHeight: dropdownMaxHeight }"
              @scrolltolower="onReachBottom"
            >
              <view 
                class="dropdown-item"
                v-for="item in filteredAdslList"
                :key="item.id"
                @click="selectItem(item)"
                :class="{ 'selected': selectedAdsl && selectedAdsl.id === item.id }"
              >
                <view class="item-content">
                  <view class="item-main">
                    <text class="item-name">{{ item.jzxm }}</text>
                    <text class="item-phone">{{ item.zjlxdh }}</text>
                  </view>
                  <view class="item-address">{{ item.address }}</view>
                </view>
                <view class="item-check" v-if="selectedAdsl && selectedAdsl.id === item.id">
                  <uni-icons type="checkmarkempty" size="18" color="#8B5CF6"></uni-icons>
                </view>
              </view>
              
              <!-- 加载更多 -->
              <view class="dropdown-loading" v-if="loading">
                <uni-load-more status="loading"></uni-load-more>
              </view>
              
              <!-- 无搜索结果 -->
              <view class="dropdown-empty" v-if="filteredAdslList.length === 0 && allAdslList.length > 0 && !loading">
                <uni-icons type="search" size="40" color="#ccc"></uni-icons>
                <text class="empty-text">未找到匹配的资料</text>
              </view>
              
              <!-- 无数据 -->
              <view class="dropdown-empty" v-if="allAdslList.length === 0 && !loading">
                <uni-icons type="inbox" size="40" color="#ccc"></uni-icons>
                <text class="empty-text">暂无数据</text>
              </view>
            </scroll-view>
          </view>
        </view>
      </view>
      
      <!-- 选中资料信息 -->
      <view class="selected-info" v-if="selectedAdsl">
        <view class="info-header">
          <text class="info-title">当前选中资料</text>
        </view>
        <view class="info-content">
          <view class="info-row">
            <text class="info-label">机主姓名：</text>
            <text class="info-value">{{ selectedAdsl.jzxm }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">联系电话：</text>
            <text class="info-value">{{ selectedAdsl.zjlxdh }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">地址：</text>
            <text class="info-value">{{ selectedAdsl.address }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">当前GUID：</text>
            <text class="info-value guid-text">{{ selectedAdsl.jguid || '无' }}</text>
          </view>
        </view>
      </view>
      
      <!-- 新GUID输入 -->
      <view class="guid-input-section" v-if="selectedAdsl">
        <view class="section-title">
          <text class="title-text">新设备GUID</text>
        </view>
        <view class="input-wrapper">
          <uni-easyinput 
            v-model="newGuid" 
            placeholder="请输入新设备的GUID"
            :clearable="true"
          ></uni-easyinput>
        </view>
      </view>
      
      <!-- 替换原因输入 -->
      <view class="reason-input-section" v-if="selectedAdsl">
        <view class="section-title">
          <text class="title-text">替换原因</text>
        </view>
        <view class="input-wrapper">
          <uni-easyinput 
            v-model="replaceReason" 
            placeholder="请输入设备替换原因"
            :clearable="true"
            type="textarea"
            :autoHeight="true"
            :maxlength="200"
          ></uni-easyinput>
        </view>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-section" v-if="selectedAdsl">
        <button 
          class="replace-btn" 
          @click="handleReplaceDevice"
          :disabled="!newGuid.trim() || !replaceReason.trim() || isSubmitting"
        >
          {{ isSubmitting ? '提交中...' : '确认替换' }}
        </button>
      </view>
      
      <!-- 无数据状态 -->
      <view class="empty-state" v-if="allAdslList.length === 0 && !loading">
        <uni-icons type="inbox" size="60" color="#ccc"></uni-icons>
        <text class="empty-text">暂无资料数据</text>
      </view>
      
      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading && allAdslList.length === 0">
        <uni-load-more status="loading"></uni-load-more>
      </view>
    </view>
    
    <!-- 遮罩层 -->
    <view class="dropdown-mask" v-if="isDropdownOpen" @click="hideDropdown"></view>
  </view>
</template>

<script>
import request from '@/utils/request'

export default {
  data() {
    return {
      searchText: '',
      loading: false,
      isSubmitting: false,
      selectedAdslId: null,
      selectedAdsl: null,
      newGuid: '',
      replaceReason: '',
      adslList: [],
      filteredAdslList: [],
      allAdslList: [],
      pageNum: 1,
      pageSize: 50,
      hasMore: true,
      isDropdownOpen: false,
      dropdownMaxHeight: '400px',
      inputFocus: false,
      searchTimer: null,
      requestSeq: 0,        // 新增：请求序号，用于防止竞态
      lastAppliedSeq: 0     // 新增：最后一次成功应用的序号
    }
  },
  onLoad() {
    this.loadAdslList();
  },
  onPullDownRefresh() {
    this.pageNum = 1;
    this.hasMore = true;
    this.loadAdslList().then(() => uni.stopPullDownRefresh());
  },
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.pageNum++;
      this.loadAdslList();
    }
  },
  methods: {
    goBack() { uni.navigateBack(); },

    // 加载资料列表（支持传入固定查询词与请求标识）
    async loadAdslList(passedQuery = null, seqAtCall = null) {
      if (this.loading) return;
      this.loading = true;
      try {
        const query = passedQuery !== null ? passedQuery : (this.searchText || '').trim();
        const params = { pageNum: this.pageNum, pageSize: this.pageSize, country: 259 };
        if (query) {
          // 多字段同时传递，后端按需匹配
          params.address = query;   // 地址
          // params.jzxm = query;      // 机主姓名
          // params.zjlxdh = query;    // 手机号
        }
        const response = await request({ url: '/door/adsl/list', method: 'get', params });
        // 竞态保护：仅当本次seq仍是最新时才应用
        if (seqAtCall !== null && seqAtCall !== this.requestSeq) {
          return; // 丢弃过期响应
        }
        if (response.code === 200) {
          const newData = response.rows || [];
          if (this.pageNum === 1) {
            this.adslList = newData;
            this.allAdslList = newData;
            this.filteredAdslList = newData;
          } else {
            this.adslList = [...this.adslList, ...newData];
            this.allAdslList = [...this.allAdslList, ...newData];
            this.filteredAdslList = [...this.filteredAdslList, ...newData];
          }
          this.hasMore = newData.length === this.pageSize;
          this.lastAppliedSeq = this.requestSeq;
        } else {
          this.$modal.msgError(response.msg || '获取资料列表失败');
        }
      } catch (e) {
        console.error('加载资料列表失败:', e);
        this.$modal.msgError('网络异常，请稍后重试');
      } finally {
        this.loading = false;
      }
    },

    showDropdown() {
      this.isDropdownOpen = true;
      this.inputFocus = true;
      if (this.allAdslList.length === 0 && !this.loading) {
        this.pageNum = 1;
        this.hasMore = true;
        this.loadAdslList();
      }
    },

    // 处理输入变化（防抖 + 竞态保护）
    onInputChange(e) {
      const newValue = e && e.detail ? e.detail.value : (e && e.target ? e.target.value : '');
      this.searchText = typeof newValue === 'string' ? newValue : String(newValue || '');
      this.isDropdownOpen = true;
      this.inputFocus = true;
      // 防抖
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        this.performSearch();
      }, 300);
    },

    async performSearch() {
      // 每次搜索提升序号，后返回的旧请求将被丢弃
      this.requestSeq += 1;
      const currentSeq = this.requestSeq;
      // 重置到第一页，不立即清空已有数据，避免闪烁
      this.pageNum = 1;
      this.hasMore = true;
      await this.loadAdslList((this.searchText || '').trim(), currentSeq);
    },

    selectItem(item) {
      this.selectedAdsl = item;
      this.selectedAdslId = item.id;
      this.searchText = `${item.jzxm} - ${item.zjlxdh} - ${item.address}`;
      this.isDropdownOpen = false;
      this.inputFocus = false;
      this.newGuid = '';
      this.replaceReason = '';
    },

    clearSelection() {
      this.selectedAdsl = null;
      this.selectedAdslId = null;
      this.searchText = '';
      this.newGuid = '';
      this.replaceReason = '';
      this.isDropdownOpen = false;
      this.inputFocus = false;
      this.pageNum = 1;
      this.hasMore = true;
      this.loadAdslList('');
    },

    // 执行设备替换（保持不变）
    async handleReplaceDevice() {
      if (!this.selectedAdsl) {
        this.$modal.msgError('请先选择资料');
        return;
      }
      
      if (!this.newGuid.trim()) {
        this.$modal.msgError('请输入新设备GUID');
        return;
      }
      
      if (!this.replaceReason.trim()) {
        this.$modal.msgError('请输入替换原因');
        return;
      }
      
      // 确认对话框
      const confirmResult = await this.showConfirmDialog();
      if (!confirmResult) return;
      
      this.isSubmitting = true;
      try {
        const response = await request({
          url: '/door/adsl/changeGuid',
          method: 'post',
          data: {
            id: this.selectedAdsl.id,
            xguid: this.newGuid.trim(),
            reason: this.replaceReason.trim() // 添加替换原因
          }
        });
        
        if (response.code === 200) {
          this.$modal.msgSuccess('设备替换成功');
          
          // 更新本地数据
          const index = this.adslList.findIndex(item => item.id === this.selectedAdsl.id);
          if (index !== -1) {
            this.adslList[index].jguid = this.newGuid.trim();
            this.selectedAdsl.jguid = this.newGuid.trim();
          }
          
          // 重置表单
          this.newGuid = '';
          this.replaceReason = ''; // 重置替换原因
        } else {
          this.$modal.msgError(response.msg || '设备替换失败');
        }
      } catch (error) {
        console.error('设备替换失败:', error);
        this.$modal.msgError('网络异常，请稍后重试');
      } finally {
        this.isSubmitting = false;
      }
    },
    
    // 显示确认对话框
    showConfirmDialog() {
      return new Promise((resolve) => {
        uni.showModal({
          title: '确认替换',
          content: `确定要将 ${this.selectedAdsl.jzxm} 的设备GUID从 ${this.selectedAdsl.jguid || '无'} 替换为 ${this.newGuid} 吗？\n\n替换原因：${this.replaceReason}`,
          success: (res) => {
            resolve(res.confirm);
          }
        });
      });
    },

    // 切换下拉框显示状态
    toggleDropdown() {
      this.isDropdownOpen = !this.isDropdownOpen;
      this.inputFocus = true; // 打开下拉框时聚焦input
    },

    // 隐藏下拉框
    hideDropdown() {
      this.isDropdownOpen = false;
      this.inputFocus = false; // 关闭下拉框时取消聚焦
    },

    // 聚焦input
    focusInput() {
      this.inputFocus = true;
    }
  }
}
</script>

<style lang="scss" scoped>
.device-replace-container {
  background-color: #f8f9fa;
  min-height: 100vh;
}

.content-wrapper {
  padding: 20rpx;
}

.select-section,
.selected-info,
.guid-input-section,
.reason-input-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.section-title {
  margin-bottom: 16rpx;
  
  .title-text {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
  }
}

.select-wrapper {
  margin-bottom: 0;
}

.selected-info {
  .info-header {
    margin-bottom: 16rpx;
    padding-bottom: 12rpx;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .info-title {
    font-size: 30rpx;
    font-weight: 600;
    color: #333;
  }
  
  .info-content {
    .info-row {
      display: flex;
      margin-bottom: 12rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .info-label {
        min-width: 160rpx;
        font-size: 28rpx;
        color: #666;
      }
      
      .info-value {
        flex: 1;
        font-size: 28rpx;
        color: #333;
        
        &.guid-text {
          font-family: Monaco, 'Courier New', monospace;
          background: #f5f5f5;
          padding: 4rpx 8rpx;
          border-radius: 4rpx;
          font-size: 24rpx;
        }
      }
    }
  }
}

.input-wrapper {
  .uni-easyinput {
    border-radius: 8rpx;
  }
}

.action-section {
  padding: 20rpx;
  
  .replace-btn {
    width: 100%;
    height: 88rpx;
    background: linear-gradient(135deg, #8B5CF6 0%, #7C3AED 100%);
    color: #fff;
    border: none;
    border-radius: 12rpx;
    font-size: 32rpx;
    font-weight: 600;
    
    &:disabled {
      background: #f5f5f5;
      color: #999;
    }
  }
}

.empty-state {
  text-align: center;
  padding: 100rpx 20rpx;
  
  .empty-text {
    display: block;
    margin-top: 20rpx;
    color: #999;
    font-size: 28rpx;
  }
}

.loading-state {
  padding: 40rpx 20rpx;
  text-align: center;
}

/* 自定义下拉框样式 */
.custom-select-wrapper {
  position: relative;
  margin-bottom: 0;
}

.select-input-wrapper {
  display: flex;
  align-items: center;
  padding: 12rpx 16rpx;
  border: 1px solid #e1e5e9;
  border-radius: 8rpx;
  background-color: #fff;
  cursor: pointer;
  transition: border-color 0.2s ease;

  &:focus-within {
    border-color: #8B5CF6;
    box-shadow: 0 0 8rpx rgba(139, 92, 246, 0.2);
  }

  .select-input {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    padding-right: 10rpx;
    border: none;
    outline: none;
    background-color: transparent;
    height: 40rpx;
    line-height: 40rpx;
  }

  .select-icon {
    margin-left: 10rpx;
    transition: transform 0.3s ease;
    
    &.rotate {
      transform: rotate(180deg);
    }
  }

  .clear-icon {
    margin-left: 10rpx;
    padding: 4rpx;
    border-radius: 50%;
    
    &:hover {
      background-color: #f5f5f5;
    }
  }
}

.dropdown-wrapper {
  position: absolute;
  top: calc(100% + 4rpx);
  left: 0;
  width: 100%;
  background-color: #fff;
  border: 1px solid #e1e5e9;
  border-radius: 8rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  z-index: 100;
  max-height: 400rpx;
  overflow: hidden;
}

.dropdown-list {
  max-height: 400rpx;
}

.dropdown-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx;
  cursor: pointer;
  border-bottom: 1px solid #f5f5f5;
  transition: background-color 0.2s ease;

  &:last-child {
    border-bottom: none;
  }

  &:hover {
    background-color: #f8f9fa;
  }

  &.selected {
    background-color: #f0f7ff;
    color: #8B5CF6;
  }
}

.item-content {
  flex: 1;
  margin-right: 10rpx;
}

.item-main {
  display: flex;
  align-items: center;
  margin-bottom: 4rpx;
  
  .item-name {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
    margin-right: 16rpx;
  }
  
  .item-phone {
    font-size: 24rpx;
    color: #666;
  }
}

.item-address {
  font-size: 24rpx;
  color: #999;
  line-height: 1.4;
}

.item-check {
  margin-left: 10rpx;
}

.dropdown-loading {
  padding: 20rpx 0;
  text-align: center;
}

.dropdown-empty {
  padding: 40rpx 20rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
  
  .empty-text {
    display: block;
    margin-top: 16rpx;
  }
}

.dropdown-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: transparent;
  z-index: 99;
}
</style> 